// pages/draft/draft.js
const http = require('../../utils/http.js')

Page({
  /**
   * 页面的初始数据
   */
  data: {
    drafts: [], // 草稿列表
    loading: false, // 加载状态
    currentPage: 1, // 当前页码
    pageSize: 10, // 每页数量
    hasMore: true, // 是否有更多数据
    status: 1 // 草稿状态，1表示有效草稿
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.loadDrafts()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 页面显示时刷新数据
    this.setData({
      currentPage: 1,
      hasMore: true
    })
    this.loadDrafts()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      currentPage: 1,
      hasMore: true
    })
    this.loadDrafts()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  // onReachBottom: function () {
  //   if (this.data.hasMore && !this.data.loading) {
  //     this.loadMoreDrafts()
  //   }
  // },

  /**
   * 加载草稿列表
   */
  loadDrafts: function () {
    const that = this
    this.setData({ loading: true })

    const params = {
      url: '/p/faceDraft/list',
      method: 'GET',
      data: {
        page: that.data.currentPage,
        limit: 100,
        status: 1
      },
      header: {
        'Content-Type': 'application/json',
        'Authorization': wx.getStorageSync('token')
      },
      callBack: res => {
        console.log('获取草稿列表成功===:', res)
        that.setData({ loading: false })
        
        if (res) {
          const records = res || []
          // const total = res.data.total || 0
          
          that.setData({
            drafts: records,
            // hasMore: records.length >= that.data.pageSize
          })
        } else {
          wx.showToast({
            title: '获取草稿列表失败',
            icon: 'none'
          })
        }
      },
      errCallBack: err => {
        console.error('获取草稿列表失败:', err)
        that.setData({ loading: false })
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        })
      }
    }
    
    return http.request(params)
  },

  /**
   * 加载更多草稿
   */
  loadMoreDrafts: function () {
    const that = this
    const nextPage = this.data.currentPage + 1
    
    this.setData({ loading: true })

    const params = {
      url: '/p/faceDraft/list',
      method: 'GET',
      data: {
        page: nextPage,
        limit: that.data.pageSize,
        status: 1
      },
      header: {
        'Content-Type': 'application/json',
        'Authorization': wx.getStorageSync('token')
      },
      callBack: res => {
        console.log('加载更多草稿成功:', res)
        that.setData({ loading: false })
        
        if (res && res.code === 200 && res.data) {
          const records = res.data.records || []
          const newDrafts = [...that.data.drafts, ...records]
          
          that.setData({
            drafts: newDrafts,
            currentPage: nextPage,
            hasMore: records.length >= that.data.pageSize
          })
        } else {
          wx.showToast({
            title: '加载更多草稿失败',
            icon: 'none'
          })
        }
      },
      errCallBack: err => {
        console.error('加载更多草稿失败:', err)
        that.setData({ loading: false })
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        })
      }
    }
    
    http.request(params)
  },

  /**
   * 查看草稿详情
   */
  viewDraft: function (e) {
    console.log('查看草稿详情:', e.currentTarget.dataset)
    const draftId = e.currentTarget.dataset.id
    if (!draftId) {
      wx.showToast({
        title: '草稿ID无效',
        icon: 'none'
      })
      return
    }

    // 跳转到自定义页面，传入草稿ID
    wx.navigateTo({
      url: '/pages/customize/customize?draftId=' + draftId
    })
  },

  /**
   * 删除草稿
   */
  deleteDraft: function (e) {
    const draftId = e.currentTarget.dataset.id
    const that = this
    
    if (!draftId) {
      wx.showToast({
        title: '草稿ID无效',
        icon: 'none'
      })
      return
    }

    wx.showModal({
      title: '确认删除',
      content: '确定要删除这个草稿吗？',
      success: function (res) {
        if (res.confirm) {
          that.doDeleteDraft(draftId)
        }
      }
    })
  },

  /**
   * 执行删除草稿操作
   */
  doDeleteDraft: function (draftId) {
    const that = this
    
    wx.showLoading({
      title: '删除中...'
    })

    const params = {
      url: `/p/faceDraft/delete`,
      method: 'DELETE',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': wx.getStorageSync('token')
      },
      data:{
        draftId: draftId
      },
      callBack: res => {
        wx.hideLoading()
        
        if (res && res.code === 200) {
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          })
          
          // 重新加载草稿列表
          that.setData({
            currentPage: 1,
            hasMore: true
          })
          that.loadDrafts()
        } else {
          wx.showToast({
            title: '删除失败',
            icon: 'none'
          })
        }
      },
      errCallBack: err => {
        wx.hideLoading()
        console.error('删除草稿失败:', err)
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        })
      }
    }
    
    http.request(params)
  },

  /**
   * 创建新草稿
   */
  createDraft: function () {
    // 跳转到自定义页面创建新草稿
    wx.navigateTo({
      url: 'pages/customize/customize'
    })
  }
})